package cn.buglife.concurrent.latch;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * CountDownLatch 是一个并发构造，它允许一个或多个线程等待一系列指定操作的完成。
 *
 * <p>
 * CountDownLatch以一个给定的数量初始化。countDown() 每被调用一次，这一数量就减一。通过调用 await()
 * 方法，线程可以阻塞等待这一数量到达零。
 * </p>
 * 
 * @author zhangjun
 */
public class CountDownLatchSample {

  public static void main(String[] args) {
    CountDownLatch downLatch = new CountDownLatch(5);

    Runnable wait = () -> {
      try {
        System.out.println("准备阻塞");

        //等待其他线程执行完
        downLatch.await();
        System.out.println("result" + downLatch.getCount());
      } catch (InterruptedException e) {
        e.printStackTrace();
      }

      System.out.println("released");
    };

    Runnable consume = () -> {
      try {
        Thread.sleep(1000);
        downLatch.countDown();
        System.out.println("减少1次");
        System.out.println(downLatch.getCount());
        Thread.sleep(1000);
        downLatch.countDown();
        System.out.println("减少2次");
        System.out.println(downLatch.getCount());

        Thread.sleep(1000);
        downLatch.countDown();
        System.out.println("减少3次");
        System.out.println(downLatch.getCount());

        Thread.sleep(1000);
        downLatch.countDown();

        System.out.println("减少4次");
        System.out.println(downLatch.getCount());
        Thread.sleep(1000);
        downLatch.countDown();

        System.out.println("减少5次");
        System.out.println(downLatch.getCount());
      } catch (InterruptedException e) {
        e.printStackTrace();
      }

    };
    new Thread(consume).start();
    new Thread(wait).start();
    System.out.println(downLatch.getCount());
  }
}
